package com.sunyard.utils;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.RandomUtil;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import com.sunyard.constant.manage.RegexConst;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 * @author ：xiaog.li
 * @date ： 2019/5/29 21:51
 * @description：Hex工具类
 * @version: 1.0$
 */
public class StringUtil {
    /**
     * 用于建立十六进制字符的输出的小写字符数组
     */
    private static final char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * 用于建立十六进制字符的输出的大写字符数组
     */
    private static final char[] DIGITS_UPPER = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};


    /**
     * 字符串转换成十六进制字符串
     *
     * @param String str 待转换的ASCII字符串
     * @return String 每个Byte之间空格分隔，如: [61 6C 6B]
     */
    public static String str2HexStr(String var0) {
        char[] var1 = "0123456789ABCDEF".toCharArray();
        StringBuilder var2 = new StringBuilder("");
        byte[] var3 = var0.getBytes();

        for (int var5 = 0; var5 < var3.length; ++var5) {
            int var4 = (var3[var5] & 240) >> 4;
            var2.append(var1[var4]);
            var4 = var3[var5] & 15;
            var2.append(var1[var4]);
//            var2.append(' ');
        }

        return var2.toString().trim();
    }
//    public static String str2HexStr(String str) {
//        char[] chars = "0123456789ABCDEF".toCharArray();
//        StringBuilder sb = new StringBuilder("");
//        byte[] bs = str.getBytes();
//        int bit;
//
//        for (int i = 0; i < bs.length; i++) {
//            bit = (bs[i] & 0x0f0) >> 4;
//            sb.append(chars[bit]);
//            bit = bs[i] & 0x0f;
//            sb.append(chars[bit]);
//        }
//        return sb.toString().trim();
//    }

    /**
     * 十六进制转换字符串
     *
     * @param String str Byte字符串(Byte之间无分隔符 如:[616C6B])
     * @return String 对应的字符串
     */
    public static String hexStr2Str(String hexStr) {
        String str = "0123456789ABCDEF";
        char[] hexs = hexStr.toCharArray();
        byte[] bytes = new byte[hexStr.length() / 2];
        int n;

        for (int i = 0; i < bytes.length; i++) {
            n = str.indexOf(hexs[2 * i]) * 16;
            n += str.indexOf(hexs[2 * i + 1]);
            bytes[i] = (byte) (n & 0xff);
        }
        return new String(bytes);
    }

    /**
     * bytes转换成十六进制字符串
     *
     * @param byte[] b byte数组
     * @return String 每个Byte值之间空格分隔
     */
    public static String byte2HexStr(byte[] b) {
        String stmp = "";
        StringBuilder sb = new StringBuilder("");
        for (int n = 0; n < b.length; n++) {
            stmp = Integer.toHexString(b[n] & 0xFF);
            sb.append((stmp.length() == 1) ? "0" + stmp : stmp);
        }
        return sb.toString().toUpperCase().trim();
    }

//    public static String byte2HexStr(byte[] var0) {
//        if (var0 == null) {
//            return "";
//        } else {
//            String var1 = "";
//            StringBuilder var2 = new StringBuilder("");
//
//            for (int var3 = 0; var3 < var0.length; ++var3) {
//                var1 = Integer.toHexString(var0[var3] & 255);
//                var2.append(var1.length() == 1 ? "0" + var1 : var1);
//            }
//
//            return var2.toString().toUpperCase().trim();
//        }
//    }

    /**
     * bytes字符串转换为Byte值
     *
     * @param String src Byte字符串，每个Byte之间没有分隔符
     * @return byte[]
     */
//    public static byte[] hexStr2Bytes(String src) {
//        int m = 0, n = 0;
//        int l = src.length() / 2;
//        System.out.println(l);
//        byte[] ret = new byte[l];
//        for (int i = 0; i < l; i++) {
//            m = i * 2 + 1;
//            n = m + 1;
//            ret[i] = Byte.decode("0x" + src.substring(i * 2, m) + src.substring(m, n));
//        }
//        return ret;
//    }

    /**
     * String的字符串转换成unicode的String
     *
     * @param String strText 全角字符串
     * @return String 每个unicode之间无分隔符
     * @throws Exception
     */
    public static String strToUnicode(String strText) throws Exception {
        char c;
        StringBuilder str = new StringBuilder();
        int intAsc;
        String strHex;
        for (int i = 0; i < strText.length(); i++) {
            c = strText.charAt(i);
            intAsc = (int) c;
            strHex = Integer.toHexString(intAsc);
            if (intAsc > 128) {
                str.append("\\u" + strHex);
            } else
            // 低位在前面补00
            {
                str.append("\\u00" + strHex);
            }
        }
        return str.toString();
    }

    /**
     * unicode的String转换成String的字符串
     *
     * @param String hex 16进制值字符串 （一个unicode为2byte）
     * @return String 全角字符串
     */
    public static String unicodeToString(String hex) {
        int t = hex.length() / 6;
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < t; i++) {
            String s = hex.substring(i * 6, (i + 1) * 6);
            // 高位需要补上00再转
            String s1 = s.substring(2, 4) + "00";
            // 低位直接转
            String s2 = s.substring(4);
            // 将16进制的string转为int
            int n = Integer.valueOf(s1, 16) + Integer.valueOf(s2, 16);
            // 将int转换为字符
            char[] chars = Character.toChars(n);
            str.append(new String(chars));
        }
        return str.toString();
    }


    /**
     * 将字节数组转换为十六进制字符数组
     *
     * @param data byte[]
     * @return 十六进制char[]
     */
    public static char[] encodeHex(byte[] data) {
        return encodeHex(data, true);
    }

    /**
     * 将字节数组转换为十六进制字符数组
     *
     * @param data        byte[]
     * @param toLowerCase <code>true</code> 传换成小写格式 ， <code>false</code> 传换成大写格式
     * @return 十六进制char[]
     */
    public static char[] encodeHex(byte[] data, boolean toLowerCase) {
        return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
    }

    /**
     * 将字节数组转换为十六进制字符数组
     *
     * @param data     byte[]
     * @param toDigits 用于控制输出的char[]
     * @return 十六进制char[]
     */
    protected static char[] encodeHex(byte[] data, char[] toDigits) {
        int l = data.length;
        char[] out = new char[l << 1];
        // two characters form the hex value.
        for (int i = 0, j = 0; i < l; i++) {
            out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
            out[j++] = toDigits[0x0F & data[i]];
        }
        return out;
    }

    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param data byte[]
     * @return 十六进制String
     */
    public static String encodeHexStr(byte[] data) {
        return encodeHexStr(data, true);
    }

    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param data        byte[]
     * @param toLowerCase <code>true</code> 传换成小写格式 ， <code>false</code> 传换成大写格式
     * @return 十六进制String
     */
    public static String encodeHexStr(byte[] data, boolean toLowerCase) {
        return encodeHexStr(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
    }

    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param data     byte[]
     * @param toDigits 用于控制输出的char[]
     * @return 十六进制String
     */
    protected static String encodeHexStr(byte[] data, char[] toDigits) {
        return new String(encodeHex(data, toDigits));
    }

    /**
     * 将十六进制字符数组转换为字节数组
     *
     * @param data 十六进制char[]
     * @return byte[]
     * @throws RuntimeException 如果源十六进制字符数组是一个奇怪的长度，将抛出运行时异常
     */
    public static byte[] decodeHex(char[] data) {

        int len = data.length;

        if ((len & 0x01) != 0) {
            throw new RuntimeException("Odd number of characters.");
        }

        byte[] out = new byte[len >> 1];

        // two characters form the hex value.
        for (int i = 0, j = 0; j < len; i++) {
            int f = toDigit(data[j], j) << 4;
            j++;
            f = f | toDigit(data[j], j);
            j++;
            out[i] = (byte) (f & 0xFF);
        }

        return out;
    }

    /**
     * 将十六进制字符转换成一个整数
     *
     * @param ch    十六进制char
     * @param index 十六进制字符在字符数组中的位置
     * @return 一个整数
     * @throws RuntimeException 当ch不是一个合法的十六进制字符时，抛出运行时异常
     */
    protected static int toDigit(char ch, int index) {
        int digit = Character.digit(ch, 16);
        if (digit == -1) {
            throw new RuntimeException("Illegal hexadecimal character " + ch
                    + " at index " + index);
        }
        return digit;
    }

    /**
     * @author xiaog.li
     * @date 2019/7/25 8:55
     */
    public static String repeat(char padChar, int repeat) {
        if (repeat <= 0) {
            return "";
        }
        char[] buf = new char[repeat];

        for (int i = 0; i < repeat; ++i) {
            buf[i] = padChar;
        }
        return new String(buf);
    }

    public static String byteToStr(byte[] var0) {
        String var1 = "";

        var1 = new String(var0, StandardCharsets.ISO_8859_1);

        return var1;
    }

    public static byte[] hexStr2Bytes(String var0) {
        if (var0 == null || "".equals(var0)) {
            return null;
        } else {
            boolean var1 = false;
            boolean var2 = false;
            if (var0.length() % 2 != 0) {
                var0 = "0" + var0;
            }

            int var3 = var0.length() / 2;
            byte[] var4 = new byte[var3];

            for (int var5 = 0; var5 < var3; ++var5) {
                int var6 = var5 * 2 + 1;
                int var7 = var6 + 1;
                var4[var5] = Integer.decode("0x" + var0.substring(var5 * 2, var6) + var0.substring(var6, var7)).byteValue();
            }

            return var4;
        }
    }

    /**
     * 隐藏某些特殊值
     *
     * @param value   原值
     * @param padChar 替换的字符
     * @return
     */
    public static String replace(String value, char padChar) {
        if (value == null || "".equals(value)) {
            return value;
        }
        int len = value.length();
        if (len <= 1) {
            return value;
        }
        if (len == 2) {
            return String.valueOf(value.charAt(0)).concat("*");
        }

        if (len >= 3 && len <= 10) {
            int startLen, centreLen, endLen;
            startLen = Math.floorDiv(len, 3);
            endLen = Math.floorDiv(len, 3);
            centreLen = len - startLen - endLen;
            String padChars = StringUtil.repeat(padChar, centreLen);
            return value.replaceAll("(.{" + startLen + "})(.{" + centreLen + "})(.{" + endLen + "})", "$1" + padChars + "$3");
        }
        String padChars = StringUtil.repeat(padChar, len - 10);
        return value.replaceAll("(.{6})(.{" + (len - 10) + "})(.{4})", "$1" + padChars + "$3");
    }

    /**
     * 将字符串某些值 替换成星号
     *
     * @author xiaog.li
     * @date 2019/7/30 9:48
     */
    public static String replace(String value) {
        return replace(value, '*');
    }


    /**
     * 左补0
     *
     * @param str
     * @param strLength 补0后的最大长度
     * @return
     */
    public static String addLeftZeroForNum(String str, int strLength) {
        int strLen = str.length();
        if (strLen < strLength) {
            while (strLen < strLength) {
                StringBuffer sb = new StringBuffer();
                sb.append("0").append(str);
                str = sb.toString();
                strLen = str.length();
            }
        }
        return str;
    }

    /**
     * 右补0
     *
     * @param str
     * @param strLength 补0后的最大长度
     * @return
     */
    public static String addRightSZeroForNum(String str, int strLength) {
        int strLen = str.length();
        if (strLen < strLength) {
            while (strLen < strLength) {
                StringBuffer sb = new StringBuffer();
                sb.append(str).append("0");
                str = sb.toString();
                strLen = str.length();
            }
        } else if (strLen > strLength) {
            str = str.substring(0, strLength);
        }
        return str;
    }

    /**
     * 右补空格
     *
     * @param str
     * @param strLength 补空格后的最大长度
     * @return
     */
    public static String addRightSpaceChar(String str, int strLength) {
        if (str == null || "null".equals(str)) {
            str = "";
        }
        int strLen = str.length();
        if (strLen < strLength) {
            while (strLen < strLength) {
                StringBuffer sb = new StringBuffer();
                sb.append(str).append(' ');
                str = sb.toString();
                strLen = str.length();
            }
        }
        return str;
    }

    /**
     * 定长 右补空格
     *
     * @param str
     * @param strLength 补空格后的最大长度
     * @return
     */
    public static String addRight(String str, int strLength) {
        if (str == null || "null".equals(str)) {
            str = "";
        }
        int strLen = str.length();
        if (strLen < strLength) {
            while (strLen < strLength) {
                StringBuffer sb = new StringBuffer();
                sb.append(str).append(' ');
                str = sb.toString();
                strLen = str.length();
            }
        } else if (strLen > strLength) {
            str = str.substring(0, strLength);
        }
        return str;
    }

    /**
     * 右补空格
     *
     * @param str
     * @param strLength 补空格后的最大长度
     * @return
     */
    public static String dtcAddRightSpaceChar(String str, int strLength) {
        if (str == null || "null".equals(str)) {
            str = "";
        }

        int strLen = checkStrLen(str);

        if (strLen < strLength) {
            while (strLen < strLength) {
                StringBuffer sb = new StringBuffer();
                sb.append(str).append(' ');
                str = sb.toString();
                strLen = checkStrLen(str);
            }
        }
        return str;
    }

    private static int checkStrLen(String str) {
        int strLen = 0;
        if (!str.matches(RegexConst.CONTAINS_CHINESE)) {
            //  不包含中文
            strLen = str.length();
        } else {
            // 包含中文，按照gbk等于2个字节处理
            for (int i = 0; i < str.length(); i++) {
                String temp = str.substring(i, i + 1);
                if (temp.matches(RegexConst.CONTAINS_CHINESE)) {
                    strLen = strLen + 2;
                } else {
                    strLen = strLen + 1;
                }
            }
        }
        return strLen;
    }


    /**
     * 随机生成数字字符串
     *
     * @param nLen 字符串长度
     * @return
     */
    public static String radomString(int nLen) {
        String result = "";
        for (int i = 0; i < nLen; i++) {
            int intVal = RandomUtil.randomInt(0, 10);
            result += Convert.toStr(intVal);
        }
        return result;
    }

    /**
     * 生成37域数据
     */
    public static String createRefNo(int nLen) {
        String dataStr = DateUtil.getDateStr(DateUtil.MMDD, new Date());
        String result = dataStr + radomString(nLen);
        return result;
    }

    public static void main(String[] args) {
        String str = "10132038290022419915000005";
        System.out.println(StringUtil.dtcAddRightSpaceChar(str, 28));
    }
}
